package org.ruoyi.knowledge.controller;

import org.ruoyi.common.core.domain.R;
import org.ruoyi.common.log.annotation.Log;
import org.ruoyi.common.log.enums.BusinessType;
import org.ruoyi.common.web.core.BaseController;
import org.ruoyi.knowledge.service.IKnowledgeInfoService;
import org.ruoyi.knowledge.service.RagflowService;
import org.ruoyi.knowledge.util.RagflowMaintenanceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * RAGFlow维护控制器
 * 用于调试和修复RAGFlow数据不一致问题
 * 
 * @author Lion Li
 * @date 2025-01-27
 */
@RestController
@RequestMapping("/knowledge/maintenance")
public class RagflowMaintenanceController extends BaseController {

    @Autowired
    private RagflowService ragflowService;

    @Autowired
    private IKnowledgeInfoService knowledgeInfoService;

    @Autowired
    private RagflowMaintenanceUtil maintenanceUtil;

    /**
     * 列出所有RAGFlow数据集
     */
    @GetMapping("/list-datasets")
    @Log(title = "RAGFlow数据集", businessType = BusinessType.EXPORT)
    public R<List<Map<String, Object>>> listRagflowDatasets() {
        try {
            List<Map<String, Object>> datasets = ragflowService.getAllDatasets();
            return R.ok(datasets);
        } catch (Exception e) {
            return R.fail("获取数据集列表失败: " + e.getMessage());
        }
    }

    /**
     * 检查RAGFlow服务状态
     */
    @GetMapping("/check-status")
    @Log(title = "RAGFlow服务状态", businessType = BusinessType.OTHER)
    public R<String> checkRagflowStatus() {
        try {
            boolean available = ragflowService.isServiceAvailable();
            if (available) {
                return R.ok("RAGFlow服务可用");
            } else {
                return R.fail("RAGFlow服务不可用");
            }
        } catch (Exception e) {
            return R.fail("检查服务状态失败: " + e.getMessage());
        }
    }

    /**
     * 同步RAGFlow数据集到本地知识库
     */
    @PostMapping("/sync-from-ragflow")
    @Log(title = "同步RAGFlow数据集", businessType = BusinessType.INSERT)
    public R<String> syncFromRagflow() {
        try {
            int count = knowledgeInfoService.syncRagflowDatasetsToLocal();
            return R.ok("成功同步 " + count + " 个知识库");
        } catch (Exception e) {
            return R.fail("同步失败: " + e.getMessage());
        }
    }

    /**
     * 强制删除RAGFlow中的指定数据集
     */
    @PostMapping("/force-delete/{datasetName}")
    @Log(title = "强制删除RAGFlow数据集", businessType = BusinessType.DELETE)
    public R<String> forceDeleteDataset(@PathVariable String datasetName) {
        try {
            boolean success = maintenanceUtil.forceDeleteDataset(datasetName);
            if (success) {
                return R.ok("已删除数据集: " + datasetName);
            } else {
                return R.fail("删除数据集失败: " + datasetName);
            }
        } catch (Exception e) {
            return R.fail("删除失败: " + e.getMessage());
        }
    }

    /**
     * 删除所有RAGFlow数据集（危险操作）
     */
    @PostMapping("/clear-all")
    @Log(title = "清空RAGFlow数据集", businessType = BusinessType.DELETE)
    public R<String> clearAllDatasets() {
        try {
            int count = knowledgeInfoService.clearAllRagflowDatasets();
            return R.ok("已删除 " + count + " 个数据集");
        } catch (Exception e) {
            return R.fail("清空失败: " + e.getMessage());
        }
    }

    /**
     * 获取数据集的文档列表
     */
    @GetMapping("/documents/{datasetName}")
    @Log(title = "获取数据集文档", businessType = BusinessType.OTHER)
    public R<List<Map<String, Object>>> getDatasetDocuments(@PathVariable String datasetName) {
        try {
            String datasetId = ragflowService.getDatasetIdByName(datasetName);
            if (datasetId == null) {
                return R.fail("未找到数据集: " + datasetName);
            }
            
            List<Map<String, Object>> documents = ragflowService.getDocuments(datasetId);
            return R.ok(documents);
        } catch (Exception e) {
            return R.fail("获取文档列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取文档的chunks
     */
    @GetMapping("/datasets/{datasetId}/documents/{documentId}/chunks")
    @Log(title = "获取文档片段", businessType = BusinessType.OTHER)
    public R<Map<String, Object>> getDocumentChunks(
            @PathVariable String datasetId,
            @PathVariable String documentId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "100") int pageSize
    ) {
        try {
            Map<String, Object> chunks = ragflowService.getDocumentChunks(datasetId, documentId, pageNum, pageSize);
            return R.ok(chunks);
        } catch (Exception e) {
            return R.fail("获取文档片段失败: " + e.getMessage());
        }
    }

    /**
     * 根据名称删除数据集
     */
    @PostMapping("/delete-by-name/{datasetName}")
    @Log(title = "删除RAGFlow数据集", businessType = BusinessType.DELETE)
    public R<String> deleteByName(@PathVariable String datasetName) {
        try {
            String datasetId = ragflowService.getDatasetIdByName(datasetName);
            if (datasetId == null) {
                return R.fail("未找到数据集: " + datasetName);
            }
            
            boolean success = ragflowService.deleteDataset(datasetId);
            if (success) {
                return R.ok("已删除数据集: " + datasetName);
            } else {
                return R.fail("删除数据集失败");
            }
        } catch (Exception e) {
            return R.fail("删除失败: " + e.getMessage());
        }
    }
}

